package com.gxhmplan.user.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gxhmplan.user.dao.UserDao;
import com.gxhmplan.user.entity.User;
import com.gxhmplan.util.Util;

@Service("userService")
public class UserServiceImpl implements UserService {
	@Resource
	UserDao userDao;
	
	/**
	 * 检查token与数据库中的token是否一致
	 */
	@Transactional(readOnly = true)
	public boolean checkToken(String id, String token) {
		User user = userDao.findUserById(id);
		return token.equals(user.getToken());
	}

	public User login(String userName, String password) {
		if (userName==null||userName.trim().isEmpty()) {
			throw new NameException("用户名不能为空");
		}
		if (password==null||password.trim().isEmpty()) {
			throw new PasswordException("密码不能为空");
		}
		User user=null;
		user = userDao.findUserByUserName(userName);
		if (user==null) {
			throw new NameException("用户名不存在");
		}
		String salt = user.getSalt();
		if (!Util.saltMd5(password, salt).equals(user.getPassword())){
			throw new PasswordException("密码不正确");
		}
		String token = UUID.randomUUID().toString();
		user.setToken(token);
		HashMap<String, Object> userInfo = new HashMap<String,Object>();
		userInfo.put("id", user.getId());
		userInfo.put("token", token);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		userInfo.put("lastLogin", sdf.format(new Date()));
		userDao.updateToken(userInfo);
		return user;
	}

	public int updateWebSet(Map<String, Object> map) {
		return userDao.updateWebSet(map);
	}

	public Map<String, Object> findWebSet() {
		return userDao.findWebSet();
	}

	public int updateBanner(Map<String, Object> map) {
		return userDao.updateBanner(map);
	}

	public Map<String, Object> findBanner() {
		return userDao.findBanner();
	}

	public int modifyPwd(String userName, String oldPwd, String newPwd, String newPwd2) {
		User user = userDao.findUserByUserName(userName);
		if (user==null) {
			throw new NameException("用户不存在");
		}
		if (oldPwd==null||oldPwd.trim().isEmpty()) {
			throw new PasswordException("原密码不能为空");
		}
		if (newPwd==null||newPwd.trim().isEmpty()) {
			throw new PasswordException("新密码不能为空");
		}
		if (!newPwd.equals(newPwd2)) {
			throw new PasswordException("两次输入的密码不一致");
		}
		if (!Util.saltMd5(oldPwd, user.getSalt()).equals(user.getPassword())) {
			throw new PasswordException("原密码不正确");
		}
		user.setPassword(Util.saltMd5(newPwd, user.getSalt()));
		return userDao.updateUser(user);
	}
}
